package com.jobsleaf.selection.provider;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.ViewPart;

public class PropertyViewer extends ViewPart implements ISelectionListener
{
	private Tree tree;
	@Override
	public void createPartControl(Composite parent)
	{
		tree = new Tree(parent, SWT.FLAT | SWT.FULL_SELECTION | SWT.MULTI);
		tree.setHeaderVisible(true);
		tree.setLinesVisible(true);
		TreeColumn column = new TreeColumn(tree, SWT.FLAT);
		column.setText("Property");
		column.setWidth(200);
		column = new TreeColumn(tree, SWT.FLAT);
		column.setText("Value");
		column.setWidth(400);
		getSite().getPage().addSelectionListener(this);  
	}

	@Override
	public void setFocus()
	{
	}

	@Override
	public void selectionChanged(IWorkbenchPart  part, ISelection selection)
	{
		Object attribute = ((StructuredSelection) selection).getFirstElement() ;
		setInput(attribute);
	}
	private void setInput(Object object)
	{
		if(tree.isDisposed())
		{
			return;
		}
		tree.removeAll();
		if(object == null || !(object instanceof  HashMap<?,?>))
			return;
		HashMap<String, String> input = (HashMap) object;
		Set< String> key = input.keySet();
		Object []keyset =  key.toArray();
		for (int i = 0; i < keyset.length; i++)
		{
			final TreeItem item = new TreeItem(tree, SWT.NONE);
			String keyString =  (String) keyset[i];
			String value = input.get(keyString);
			item.setText(0, keyString);
			if(value!= null)
			{
				item.setText(1,value );	
			}
			else
			{
				item.setText(1,"N/A" );
			}
		}
	}
	
	
}
